package com.haixee.parkdemo.common.filter;


import com.haixee.parkdemo.common.context.WebContextHolder;
import com.haixee.parkdemo.common.response.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 审计：记录日志
 *
 * @author GUIFENG GUO
 * 2020/3/22 9:24
 */
@Slf4j
@WebFilter(filterName = "AuditFilter", urlPatterns = {"/*"})
@Order(value = Integer.MAX_VALUE - 600)
@Configuration
public class AuditFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        CommonLog commonLog = LogUtil.makeBasicLog(request);
//
//        WebContextHolder.add(commonLog);

        long startTime = System.currentTimeMillis();

        filterChain.doFilter(servletRequest, servletResponse);

        // 计时
        double latency = (System.currentTimeMillis() - startTime);
//        commonLog.setLatency(latency);

        // 打印日志
        LogUtil.printLog(request, latency, startTime);

        WebContextHolder.remove();
    }
}
